# -*- coding: UTF-8 -*-
# @description : python
# @Author : zyl
# @contact : zyl@mxsoft.com
# @Time : 2021/9/29 17:59
# @Remark:
from functools import wraps
from mxsoftpy import TreeDB
from mxsoftpy import globals as g

db = TreeDB()


def modify(f):
    """
    多租户代码增加
    固定 tree open 中的 sub_key
    每个IP接口处增加 open 分支如果有租户 ID 打开参数为 租户键 否则为所有的键
    """

    @wraps(f)
    def func(self, *args, **kwargs):
        account_id = g.request().headers['accountid']  # 获取租户ID

        def new_open(*a, **k):
            a = list(a)
            if a[1] != '' and k['file'] == 'ipctrl':
                sub_key = a[1].split('\\')
                if account_id:  # 有租户ID才会走多租户逻辑
                    sub_key.insert(1, account_id)
                    sub_key.insert(1, 'tenant')
                else:
                    sub_key.insert(1, account_id)
                    sub_key.insert(1, 'all')
                a[1] = '\\'.join(a[1])
            # 改写 self.tree.open 传参
            res = db.open(*tuple(a), **k)
            return res

        self.tree.open = new_open
        return f(self, *args, **kwargs)

    return func
